<template>
  <div>
    <div class="w-full h-[55px] sm:h-[72px]"></div>
    <ErrorBoundary :error="error">
      <div v-if="isLoading" class="flex justify-center py-12">
        <!-- 加载中 -->
        <div
          class="animate-spin h-8 w-8 border-4 border-blue-500 rounded-full border-t-transparent"
        ></div>
      </div>

      <div v-else>
        <!-- 面包屑导航 -->
        <div class="max-w-full mb-6 xl:px-2 lg:px-2 md:px-4 px-4 mt-6">
          <div class="max-w-screen-2xl mx-auto">
            <nuxt-link
              :to="`${homepagePath}/`"
              class="justify-start text-white/60 text-base font-normal"
              >{{ t("common.breadcrumb.home") }}</nuxt-link
            >
            <span class="text-white/60 text-base font-normal px-2"> / </span>
            <nuxt-link
              :to="`${homepagePath}/products`"
              class="text-white/60 text-base font-normal"
              >{{ t("common.breadcrumb.products") }}</nuxt-link
            >
            <span class="text-white/60 text-base font-normal px-2"> / </span>
            <nuxt-link
              v-if="product?.category"
              :to="`${homepagePath}/products?category=${encodeURIComponent(product.category)}`"
              class="text-white/60 text-base font-normal"
              >{{ product.category }}</nuxt-link
            >
            <span class="text-white/60 text-base font-normal px-2"> / </span>
            <span class="text-white text-base font-normal">{{
              product?.title || product?.name
            }}</span>
          </div>
        </div>

        <!-- 产品详情内容 -->
        <div
          v-if="product"
          class="max-w-full mb-12 md:mb-20 lg:mb-32 xl:px-2 lg:px-2 md:px-4 px-4"
        >
          <div class="max-w-screen-2xl mx-auto">
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 lg:gap-16">
              <!-- 左侧产品图片 -->
              <div
                class="flex flex-col gap-6 lg:sticky lg:top-24 self-start select-none"
              >
                <!-- 主图展示 -->
                <div
                  class="bg-zinc-900 rounded-lg p-8 relative overflow-hidden group aspect-square"
                >
                  <!-- 主图容器 - Swiper -->
                  <Swiper
                    :modules="[Navigation, Pagination, EffectFade, Thumbs]"
                    :slides-per-view="1"
                    :pagination="{
                      clickable: true,
                      dynamicBullets: true,
                      dynamicMainBullets: 3,
                    }"
                    :navigation="true"
                    :effect="'fade'"
                    :fade-effect="{ crossFade: true }"
                    :thumbs="{ swiper: thumbsSwiper }"
                    class="w-full h-full product-swiper"
                    @swiper="swiperInstance = $event"
                    @slideChange="currentSlideIndex = $event.activeIndex"
                  >
                    <SwiperSlide
                      v-for="(image, slideIndex) in [
                        product.image,
                        ...(product.gallery || []),
                      ]"
                      :key="slideIndex"
                    >
                      <div class="relative w-full h-full">
                        <!-- 当前图片 -->
                        <img
                          :src="image"
                          :alt="`${product.name} - ${t('products.image', {
                            index: slideIndex + 1,
                          })}`"
                          class="w-full h-full object-contain rounded-lg transition-all duration-500"
                          :class="{
                            'opacity-0': isSlideThumbnailLoading[slideIndex],
                            'opacity-100':
                              !isSlideThumbnailLoading[slideIndex] &&
                              !slideThumbnailErrors[slideIndex],
                          }"
                          @load="handleSlideImageLoad(slideIndex)"
                          @error="handleSlideImageError(slideIndex)"
                        />

                        <!-- 加载状态 -->
                        <div
                          v-if="isSlideThumbnailLoading[slideIndex]"
                          class="absolute inset-0 flex items-center justify-center bg-zinc-800/50 z-10"
                        >
                          <div
                            class="animate-spin h-8 w-8 border-4 border-blue-500 rounded-full border-t-transparent"
                          ></div>
                        </div>

                        <!-- 错误提示 -->
                        <div
                          v-if="slideThumbnailErrors[slideIndex]"
                          class="absolute inset-0 flex items-center justify-center bg-red-900/50 z-20"
                        >
                          <div class="flex flex-col items-center gap-2">
                            <span class="text-white">{{
                              t("products.imageLoadError")
                            }}</span>
                            <button
                              @click.stop="retryLoadSlideImage(slideIndex)"
                              class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors duration-300"
                            >
                              {{ t("products.retry") }}
                            </button>
                          </div>
                        </div>
                      </div>
                    </SwiperSlide>
                  </Swiper>

                  <!-- 全局加载状态 - 仅在所有图片都未加载完成时显示 -->
                  <div
                    v-if="isInitialLoading"
                    class="absolute inset-0 flex items-center justify-center bg-zinc-900/80 z-30"
                  >
                    <div
                      class="animate-spin h-12 w-12 border-4 border-blue-500 rounded-full border-t-transparent"
                    ></div>
                  </div>
                </div>

                <!-- 缩略图列表 - Swiper -->
                <div
                  class="relative bg-zinc-900 rounded-lg py-6 px-8 overflow-hidden product-thumbnail-container"
                >
                  <Swiper
                    :modules="[Navigation, Thumbs, FreeMode]"
                    :slides-per-view="'auto'"
                    :space-between="12"
                    :free-mode="true"
                    :watch-slides-progress="true"
                    :navigation="{
                      nextEl: '.swiper-thumb-next',
                      prevEl: '.swiper-thumb-prev',
                    }"
                    class="thumbs-swiper"
                    @swiper="thumbsSwiper = $event"
                  >
                    <SwiperSlide
                      v-for="(image, index) in [
                        product.image,
                        ...(product.gallery || []),
                      ]"
                      :key="index"
                      class="!w-16 !h-16 md:!w-20 md:!h-20 !flex-shrink-0 cursor-pointer transition-all duration-300 relative"
                    >
                      <div
                        class="w-full h-full rounded-lg overflow-hidden thumbnail-fixed-size"
                        :class="{
                          'ring-2 ring-blue-500 ring-offset-2 ring-offset-zinc-900':
                            currentSlideIndex === index,
                          'hover:ring-1 hover:ring-blue-500/50 hover:ring-offset-1 hover:ring-offset-zinc-900':
                            currentSlideIndex !== index,
                          'opacity-50':
                            isSlideThumbnailLoading[index] ||
                            slideThumbnailErrors[index],
                        }"
                      >
                        <!-- 缩略图加载状态 -->
                        <div
                          v-if="isSlideThumbnailLoading[index]"
                          class="absolute inset-0 flex items-center justify-center bg-zinc-800/50 rounded-lg z-10"
                        >
                          <div
                            class="animate-spin h-4 w-4 border-2 border-blue-500 rounded-full border-t-transparent"
                          ></div>
                        </div>

                        <!-- 缩略图遮罩 -->
                        <div
                          class="absolute inset-0 transition-all duration-300 rounded-lg"
                          :class="{
                            'bg-black/30': currentSlideIndex === index,
                            'bg-black/0 hover:bg-black/20':
                              currentSlideIndex !== index,
                          }"
                        ></div>

                        <img
                          :src="image"
                          :alt="`${product.name} - ${t('products.image', {
                            index: index + 1,
                          })}`"
                          class="w-full h-full object-cover transition-all duration-300 rounded-lg"
                          :class="{
                            'opacity-0': isSlideThumbnailLoading[index],
                            'opacity-100':
                              !isSlideThumbnailLoading[index] &&
                              !slideThumbnailErrors[index],
                            'hover:scale-110': currentSlideIndex !== index,
                          }"
                          @load="handleSlideImageLoad(index)"
                          @error="handleSlideImageError(index)"
                        />

                        <!-- 缩略图错误提示 -->
                        <div
                          v-if="slideThumbnailErrors[index]"
                          class="absolute inset-0 flex items-center justify-center bg-red-900/50 rounded-lg"
                        >
                          <div class="flex flex-col items-center gap-1">
                            <span class="text-white text-xs">{{
                              t("products.error")
                            }}</span>
                            <button
                              @click.stop="retryLoadSlideImage(index)"
                              class="px-2 py-1 bg-blue-500 text-white text-xs rounded hover:bg-blue-600 transition-colors duration-300"
                            >
                              {{ t("products.retry") }}
                            </button>
                          </div>
                        </div>
                      </div>
                    </SwiperSlide>
                  </Swiper>

                  <!-- 缩略图导航按钮 -->
                  <button
                    class="swiper-thumb-prev absolute top-1/2 left-2 z-10 w-8 h-8 flex items-center justify-center bg-black/50 hover:bg-blue-500 rounded-full transform -translate-y-1/2 transition-all duration-300"
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      class="h-5 w-5 text-white"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M15 19l-7-7 7-7"
                      />
                    </svg>
                  </button>
                  <button
                    class="swiper-thumb-next absolute top-1/2 right-2 z-10 w-8 h-8 flex items-center justify-center bg-black/50 hover:bg-blue-500 rounded-full transform -translate-y-1/2 transition-all duration-300"
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      class="h-5 w-5 text-white"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M9 5l7 7-7 7"
                      />
                    </svg>
                  </button>
                </div>
              </div>

              <!-- 右侧产品信息 -->
              <div class="flex flex-col gap-8">
                <!-- 产品名称 -->
                <div class="bg-zinc-900 rounded-lg p-6">
                  <h1 class="text-white text-3xl font-medium mb-4">
                    {{ product.title || product.name }}
                  </h1>
                  <div class="text-stone-400 text-lg leading-relaxed">
                    {{ product.summary }}
                  </div>
                </div>

                <!-- 产品参数 -->
                <div class="bg-zinc-900 rounded-lg p-6">
                  <h2 class="text-white text-xl font-medium mb-6">
                    {{ t("products.productSpecifications") }}
                  </h2>
                  <div class="grid grid-cols-1 gap-4">
                    <div
                      class="flex justify-between items-center py-2 border-b border-zinc-800"
                    >
                      <span class="text-stone-400">{{
                        t("products.categoryTitle")
                      }}</span>
                      <span class="text-white font-medium">{{
                        product.category
                      }}</span>
                    </div>
                    <div
                      class="flex justify-between items-center py-2 border-b border-zinc-800"
                    >
                      <span class="text-stone-400">{{
                        t("products.usageTitle")
                      }}</span>
                      <span class="text-white font-medium">{{
                        product.usage?.join(", ")
                      }}</span>
                    </div>
                    <div
                      v-if="product.capacities && product.capacities.length > 0"
                      class="flex justify-between items-center py-2"
                    >
                      <span class="text-stone-400">{{
                        t("products.capacitiesTitle")
                      }}</span>
                      <span class="text-white font-medium">{{
                        product.capacities?.join(" / ")
                      }}</span>
                    </div>
                  </div>
                </div>

                <!-- 产品描述 -->
                <div
                  v-if="product.description"
                  class="bg-zinc-900 rounded-lg p-6"
                >
                  <h2 class="text-white text-xl font-medium mb-6">
                    {{ t("products.productDescription") }}
                  </h2>
                  <div
                    class="text-stone-400 leading-relaxed space-y-4 prose prose-invert max-w-none"
                  >
                    {{ product.description }}
                  </div>
                </div>

                <div class="bg-zinc-900 rounded-lg p-6">
                  <h2 class="text-white text-xl font-medium mb-6">
                    {{ t("products.detailedDescription") }}
                  </h2>
                  <div
                    class="text-stone-400 leading-relaxed space-y-4 prose prose-invert max-w-none"
                  >
                    <ContentRenderer :value="product.content" />
                  </div>
                </div>

                <!-- 相关产品 -->
                <div
                  v-if="relatedProducts.length > 0"
                  class="bg-zinc-900 rounded-lg p-6"
                >
                  <h2 class="text-white text-xl font-medium mb-6">
                    {{ t("products.relatedProducts") }}
                  </h2>
                  <div
                    class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4"
                  >
                    <nuxt-link
                      v-for="relatedProduct in relatedProducts"
                      :key="relatedProduct.id"
                      :to="`${homepagePath}/products/${relatedProduct.id}`"
                      class="group"
                    >
                      <div
                        class="bg-zinc-800 rounded-lg p-4 transition-all duration-300 hover:bg-zinc-700"
                      >
                        <div
                          class="aspect-square mb-4 overflow-hidden rounded-lg"
                        >
                          <img
                            :src="relatedProduct.image"
                            :alt="relatedProduct.title || relatedProduct.name"
                            class="w-full h-full object-cover transition-transform duration-300 group-hover:scale-110"
                          />
                        </div>
                        <h3
                          class="text-white text-lg font-medium mb-2 line-clamp-2"
                        >
                          {{ relatedProduct.title || relatedProduct.name }}
                        </h3>
                        <p class="text-stone-400 text-sm line-clamp-2">
                          {{ relatedProduct.summary }}
                        </p>
                      </div>
                    </nuxt-link>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </ErrorBoundary>
  </div>
</template>

<script setup lang="ts">
/**
 * 产品详情页面
 * 展示产品主图、参数和描述
 */
import { useErrorHandler } from "~/composables/useErrorHandler";
import { useRoute, useI18n, useAsyncData } from "#imports";
import { queryCollection } from "#imports";
import { ContentRenderer } from "#components";
import { Swiper, SwiperSlide } from "swiper/vue";
import {
  Navigation,
  Pagination,
  EffectFade,
  Thumbs,
  FreeMode,
} from "swiper/modules";
import type { Swiper as SwiperType } from "swiper";
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/pagination";
import "swiper/css/effect-fade";

const { error, isLoading } = useErrorHandler();
const route = useRoute();
const { locale, t } = useI18n();
const id = route.params.id as string;
const swiperInstance = ref<SwiperType | null>(null);
const thumbsSwiper = ref<SwiperType | null>(null);

// 图片状态
const currentSlideIndex = ref(0);
const isInitialLoading = ref(true); // 初始加载状态
const isSlideThumbnailLoading = ref<boolean[]>([]);
const slideThumbnailErrors = ref<boolean[]>([]);

// 滚动跟随相关
const scrollContainer = ref<HTMLElement | null>(null);
const isSticky = ref(false);

const homepagePath = computed(() => {
  return locale.value === "zh" ? "" : `/${locale.value}`;
});

interface Product {
  id: string;
  name: string;
  usage: string[];
  capacities: string[];
  category: string;
  categoryId: string;
  description: string;
  summary: string;
  image: string;
  gallery: string[];
  body: string;
  content?: any;
  meta?: {
    series?: string[];
    name?: string;
    title?: string;
    image?: string;
    summary?: string;
  };
  title?: string;
}

/**
 * 使用queryCollection获取产品数据
 */
const { data: productContent } = await useAsyncData(
  `product-${id}`,
  async () => {
    try {
      // 使用queryCollection从content目录获取数据
      const content = await queryCollection("content")
        .where("path", "LIKE", `/products/${locale.value}/${id}`)
        .first();
      return content;
    } catch (err) {
      console.error("Error fetching product content:", err);
      error.value = new Error(t("products.loadError"));
      return null;
    }
  }
);

/**
 * 获取分类信息
 */

const { data: categoryContent } = await useAsyncData(
  `category-${productContent.value?.meta?.categoryId}`,
  async () => {
    if (!productContent.value?.meta?.categoryId) return null;
    try {
      const content = await queryCollection("content")
        .where(
          "path",
          "LIKE",
          `/categories/${locale.value}/${productContent.value.meta?.categoryId}`
        )
        .first();
      return content;
    } catch (err) {
      console.error("Error fetching category:", err);
      return null;
    }
  },
  {
    immediate: !!productContent.value?.meta?.categoryId,
  }
);

/**
 * 使用计算属性解析产品数据
 */
const product = computed<Product | null>(() => {
  if (!productContent.value) return null;

  // 提取产品数据
  const meta = productContent.value.meta || {};

  return {
    id: id,
    name: String(meta.name || productContent.value.title || ""),
    title: String(productContent.value.title || meta.name || ""),
    usage: Array.isArray(meta.usage) ? meta.usage : [],
    capacities: Array.isArray(meta.capacities) ? meta.capacities : [],
    category: categoryContent.value?.title || "",
    categoryId: meta.categoryId || "",
    description: productContent.value.description || "",
    summary: String(meta.summary || ""),
    image: String(meta.image || ""),
    gallery: Array.isArray(meta.gallery) ? meta.gallery : [],
    body: productContent.value.body || "",
    content: productContent.value,
    meta: {
      series: Array.isArray(meta.series) ? meta.series : [],
      name: String(meta.name || ""),
      title: String(productContent.value.title || ""),
      image: String(meta.image || ""),
      summary: String(meta.summary || ""),
    },
  };
});

/**
 * 获取相关产品
 */
const { data: relatedProductsContent } = await useAsyncData(
  `related-products-${id}`,
  async () => {
    try {
      // 获取产品列表
      const content = await queryCollection("content")
        .where("path", "LIKE", `/products/${locale.value}/%`)
        .all();
      return content;
    } catch (err) {
      console.error("Error fetching related products:", err);
      return [];
    }
  }
);

/**
 * 处理相关产品数据
 */
const relatedProducts = computed(() => {
  if (!relatedProductsContent.value || !product.value) return [];

  // 获取当前产品的分类和系列
  const currentCategory = product.value.categoryId;
  const currentSeries = product.value.meta?.series || [];
  const currentProductId = id;

  return relatedProductsContent.value
    .filter((item: any) => {
      // 排除当前产品 - 多重检查确保排除
      if (item._path === `/products/${locale.value}/${id}`) return false;

      const meta = item.meta || {};
      if (meta.name === currentProductId) return false;

      const itemCategoryId = meta.categoryId || "";
      const itemSeries = Array.isArray(meta.series) ? meta.series : [];

      // 判断是否同类别或同系列
      const isSameCategory =
        currentCategory && itemCategoryId === currentCategory;
      const hasSameSeries =
        currentSeries.length > 0 &&
        itemSeries.some((series: string) => currentSeries.includes(series));

      // 返回同类别或同系列的产品
      return isSameCategory || hasSameSeries;
    })
    .map((item: any) => {
      const meta = item.meta || {};
      return {
        id: meta.name || "",
        name: meta.name || item.title || "",
        title: item.title || meta.name || "",
        image: meta.image || "",
        summary: meta.summary || "",
        category: meta.categoryId || "",
        series: Array.isArray(meta.series) ? meta.series : [],
      };
    })
    .slice(0, 6); // 最多显示6个相关产品
});

/**
 * 预加载下一张图片
 */
function preloadNextImage(image: string) {
  currentSlideIndex.value =
    (currentSlideIndex.value + 1) % (product.value?.gallery?.length || 1);
}

/**
 * 处理图片加载完成
 */
function handleSlideImageLoad(index: number) {
  isSlideThumbnailLoading.value[index] = false;
  slideThumbnailErrors.value[index] = false;

  // 检查是否所有图片都已加载
  const allImagesLoaded = isSlideThumbnailLoading.value.every(
    (status) => !status
  );
  if (allImagesLoaded) {
    isInitialLoading.value = false;
  }
}

/**
 * 处理图片加载错误
 */
function handleSlideImageError(index: number) {
  isSlideThumbnailLoading.value[index] = false;
  slideThumbnailErrors.value[index] = true;
}

/**
 * 重试加载图片
 */
function retryLoadSlideImage(index: number) {
  isSlideThumbnailLoading.value[index] = true;
  slideThumbnailErrors.value[index] = false;

  // 确定正确的图片URL
  const images = [product.value?.image, ...(product.value?.gallery || [])];
  const imageUrl = images[index];

  // 检查图片URL是否有效
  if (!imageUrl) {
    console.error("Invalid image URL:", index);
    slideThumbnailErrors.value[index] = true;
    isSlideThumbnailLoading.value[index] = false;
    return;
  }

  // 创建新的图片对象并设置超时
  const img = new Image();
  const timeoutId = setTimeout(() => {
    console.error("Image load timeout:", index);
    handleSlideImageError(index);
  }, 10000); // 10秒超时

  img.onload = () => {
    clearTimeout(timeoutId);
    console.log("Image loaded successfully:", index);
    handleSlideImageLoad(index);
  };

  img.onerror = (error) => {
    clearTimeout(timeoutId);
    console.error("Image load error:", { index, error });
    handleSlideImageError(index);
  };

  // 设置跨域属性
  img.crossOrigin = "anonymous";

  // 最后设置src以开始加载
  img.src = imageUrl;
}

// 页面加载时初始化状态
onMounted(() => {
  // 初始化缩略图加载状态数组
  const galleryLength = (product.value?.gallery?.length || 0) + 1;
  isSlideThumbnailLoading.value = new Array(galleryLength).fill(true);
  slideThumbnailErrors.value = new Array(galleryLength).fill(false);

  // 设置初始加载状态
  isInitialLoading.value = true;

  // 预加载所有缩略图
  const images = [product.value?.image, ...(product.value?.gallery || [])];
  images.forEach((image, index) => {
    if (image) {
      const img = new Image();
      img.onload = () => handleSlideImageLoad(index);
      img.onerror = () => handleSlideImageError(index);
      img.src = image;
    }
  });

  console.log("Initialized thumbnail states:", {
    loading: isSlideThumbnailLoading.value,
    errors: slideThumbnailErrors.value,
  });

  // 添加滚动监听
  scrollContainer.value = document.querySelector(".max-w-screen-2xl");
  if (scrollContainer.value) {
    window.addEventListener("scroll", handleScroll, { passive: true });
  }
});

// 清理滚动监听
onUnmounted(() => {
  if (scrollContainer.value) {
    window.removeEventListener("scroll", handleScroll);
  }
});

// 处理滚动事件
function handleScroll() {
  if (!scrollContainer.value) return;

  const containerRect = scrollContainer.value.getBoundingClientRect();
  const scrollTop = window.scrollY || document.documentElement.scrollTop;

  // 当容器顶部距离视窗顶部小于100px时，启用sticky
  isSticky.value = containerRect.top < 100;
}

// SEO优化
useHead(() => ({
  title: `${product.value?.name || "产品详情"} - Hanye`,
  meta: [
    {
      name: "description",
      content: product.value?.description || "产品详情页面",
    },
  ],
}));
</script>

<style lang="scss" scoped>
/* 隐藏滚动条但保持滚动功能 */
.scrollbar-hide {
  -ms-overflow-style: none; /* IE and Edge */
  scrollbar-width: none; /* Firefox */
}
.scrollbar-hide::-webkit-scrollbar {
  display: none; /* Chrome, Safari and Opera */
}

/* 图片过渡动画 */
.main-image {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 缩略图悬停效果 */
.thumbnail-item {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.thumbnail-item:hover {
  transform: translateY(-2px);
}

/* 缩略图选中效果 */
.thumbnail-item.selected {
  transform: scale(1.05);
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1),
    0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

/* 产品信息卡片效果 */
.info-card {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.info-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1),
    0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

/* 滚动跟随效果 */
.lg\:sticky {
  position: sticky;
  top: 6rem; /* 96px */
  transition: all 0.3s ease;
  z-index: 10;
  max-height: calc(100vh - 6rem);
  overflow-y: auto;
}

@media (max-width: 1024px) {
  .lg\:sticky {
    position: relative;
    top: 0;
    max-height: none;
  }
}

/* Swiper 样式定制 */
.product-swiper {
  :deep(.swiper-pagination-bullet) {
    background-color: white;
    opacity: 0.5;
  }

  :deep(.swiper-pagination-bullet-active) {
    opacity: 1;
    background-color: theme("colors.blue.500");
  }

  :deep(.swiper-button-next),
  :deep(.swiper-button-prev) {
    color: theme("colors.blue.500");
    background-color: rgba(0, 0, 0, 0.3);
    width: 36px;
    height: 36px;
    border-radius: 50%;

    &:after {
      font-size: 16px;
      font-weight: bold;
    }

    &:hover {
      background-color: theme("colors.blue.500");
      color: white;
    }
  }

  :deep(.swiper-button-disabled) {
    opacity: 0.35;
    cursor: auto;
    pointer-events: none;
  }

  :deep(.swiper-slide) {
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

/* 缩略图Swiper样式 */
.thumbs-swiper {
  overflow: visible;
  padding: 0.25rem;
  min-height: 6rem;

  :deep(.swiper-wrapper) {
    align-items: center;
    display: flex;
    min-height: 6rem;
  }

  :deep(.swiper-slide) {
    width: auto;
    height: auto;
    opacity: 0.7;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  :deep(.swiper-slide-thumb-active) {
    opacity: 1;
    transform: scale(1.05);
    z-index: 1;
  }
}

/* 自定义缩略图导航按钮 */
.swiper-thumb-next,
.swiper-thumb-prev {
  &:focus {
    outline: none;
  }

  &.swiper-button-disabled {
    opacity: 0.3;
    cursor: default;
    background-color: rgba(0, 0, 0, 0.2);

    &:hover {
      background-color: rgba(0, 0, 0, 0.2);
    }
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .thumbs-swiper {
    padding: 0;

    :deep(.swiper-slide) {
      margin-right: 8px;
    }
  }

  /* 确保缩略图容器在移动设备上有足够空间 */
  .product-thumbnail-container {
    padding: 1rem;

    .swiper-thumb-prev {
      left: 0.5rem;
      width: 2rem;
      height: 2rem;
    }

    .swiper-thumb-next {
      right: 0.5rem;
      width: 2rem;
      height: 2rem;
    }
  }
}

/* 解决不同分辨率下缩略图大小问题 */
.thumbnail-fixed-size {
  width: 100%;
  height: 100%;
  aspect-ratio: 1 / 1;
  position: relative;
}
</style>
